package com.atguigu.lease.web.admin.controller.login;


import com.atguigu.lease.common.context.LoginUser;
import com.atguigu.lease.common.context.LoginUserContext;
import com.atguigu.lease.common.result.Result;
import com.atguigu.lease.common.utils.JwtUtil;
import com.atguigu.lease.model.entity.SystemUser;
import com.atguigu.lease.web.admin.mapper.SystemUserMapper;
import com.atguigu.lease.web.admin.service.LoginService;
import com.atguigu.lease.web.admin.service.SystemUserService;
import com.atguigu.lease.web.admin.vo.login.CaptchaVo;
import com.atguigu.lease.web.admin.vo.login.LoginVo;
import com.atguigu.lease.web.admin.vo.system.user.SystemUserInfoVo;
import io.jsonwebtoken.Claims;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@Tag(name = "后台管理系统登录管理")
@RestController
@RequestMapping("/admin")
public class LoginController {

    @Autowired
    private LoginService loginService;
    @Autowired
    private SystemUserService systemUserService;

    @Operation(summary = "获取图形验证码")
    @GetMapping("login/captcha")
    public Result<CaptchaVo> getCaptcha() {
        CaptchaVo captchaVo = loginService.getCaptcha();
        return Result.ok(captchaVo);
    }

    @Operation(summary = "登录")
    @PostMapping("login")
    public Result<String> login(@RequestBody LoginVo loginVo) {
        // 登录成功要返回token给前端用来存储在浏览器本地
        String token = loginService.login(loginVo);
        return Result.ok(token);
    }

    @Operation(summary = "获取登陆用户个人信息")
    @GetMapping("info")
    public Result<SystemUserInfoVo> info(HttpServletRequest request) {

//        // 获取登录用户的昵称和头像 需要 从数据查询
//        // 需要用户的id 存储在token里面 可以通过HttpServletRequest获取token 再获取 id
//        String token = request.getHeader("access_token");// 获取请求头里面的token
//        // 解析token获取负载信息
//        Claims claims = JwtUtil.parseToken(token);
//        // 从负载信息获取用户id
//        Long userId = claims.get("userId",Long.class);
//        Long userId = Long.parseLong(request.getAttribute("userId").toString());
        //  从threadLocal作用域拿数据
        LoginUser loginUser = LoginUserContext.getLoginUser();
        // 通过userId查询系统用户的数据库 获取该对象
        SystemUserInfoVo systemUserInfoVo = systemUserService.info(loginUser.getUserId());
        return Result.ok(systemUserInfoVo);
    }
}